<template>
  <div id="microModule">
    <div style="min-height:30px;display:flex;line-height:30px;padding:10px 0;border-bottom:1px #ccc solid;
    margin-bottom:10px;flex-wrap: wrap;">
      <el-button style="font-size:16px;margin:0;padding:0" type="text" @click="setShow = !setShow" icon="el-icon-files">微件中心</el-button>
      <div style="margin-left:auto" v-if="!drag_edit">
        <el-button type="primary" v-on:click="drag_edit=true" style="margin-left: auto;">启用编辑</el-button>
      </div>
      <div style="margin-left:auto" v-else>
        <el-checkbox v-model="show_grid"  @change="grid_show" style="margin:0 20px;margin-left: auto;">显示网格</el-checkbox>
        <el-button @click="initializationMMD">初始化</el-button>
        <el-button @click="stop_drag_edit">取消编辑</el-button>
        <el-button type="primary" @click="resetStart">重置</el-button>
        <el-button type="success" @click="save_drag_edit">保存</el-button>
      </div>
      <div style="width:100%;margin-top:15px;display: none;">
        <span style="margin-left:auto 5px;">列数：</span>
        <el-select v-model="selectColumnActive" @change="changeModuleColumn" placeholder="3" style="width:80px">
          <el-option
            v-for="item in selectColumn"
            :key="item.id"
            :label="item.id"
            :value="item.value">
          </el-option>
        </el-select>
      </div>
    </div>

    <!----微件中心---->
    <div ref="MicroAssemblyCenter" v-show="setShow" class="MicroAssemblyCenter">
      <div class="MicroAssemblyCenter-title">
        <i class="el-icon-s-tools" style="margin-right:15px"></i>微件中心
        <el-button  @click="setShow = false"  type="text" style="margin-left:auto;font-size:18px;font-weight: bold;" icon="el-icon-close"></el-button>
      </div>
     
      <el-collapse v-model="MALactiveNames">
        <!-- <el-collapse-item name="1">
          <template slot="title">
            <i class="header-icon el-icon-s-open"></i>主题皮肤
          </template>
          <div></div>
        </el-collapse-item> -->
        <el-collapse-item name="1">
          <template slot="title">
            <i class="header-icon el-icon-menu" style="margin-right:15px"></i>订阅内容
          </template>
          <div class="MALactiveItem" v-for="item in drag_all_modules.slice(0,5)" :key="item.id">
            <span>{{item.title}}</span>
            <el-switch @change="changeMDshow" v-model="item.show" style="margin-left:auto;"></el-switch>
          </div>
        </el-collapse-item>

        <el-collapse-item name="2">
          <template slot="title">
            <i class="header-icon el-icon-time" style="margin-right:15px"></i>日常组件
          </template>
          <div class="MALactiveItem" v-for="item in drag_all_modules.slice(5,9)" :key="item.id">
            <span>{{item.title}}</span>
            <el-switch @change="changeMDshow" v-model="item.show" style="margin-left:auto;"></el-switch>
          </div>
        </el-collapse-item>
      </el-collapse>
    </div>

    <!----拖拽布局↓---->
    <div ref="drag_dom" style="overflow: visible;" class="g-drag g-drag-edit" :class="{'g-drag-edit':drag_edit,'g-drag-edit-grid':show_grid&&drag_edit}">
      <div v-for="(item,index) in drag_all_modules"  :id="item.id" :key="index" class="g-drag-item" :grid-x="item.position.x" 
        :grid-y="item.position.y" :grid-w="item.position.w" :grid-h="item.position.h" v-if="item.show">
        <div class="microModule-box">
          <div class="microModule-box-tile">
            <span>{{item.title}}</span>
            <div style="margin-left:auto;display: flex;" v-if="drag_edit">
              <el-button type="text" icon="el-icon-circle-plus-outline" v-if="item.id==='mm_0'" title="新增功能"></el-button>
              <el-button class="move_event_btn" type="text" icon="el-icon-rank" title="移动组件"></el-button>
              <el-button type="text" icon="el-icon-close" @click="close_module(index)" title="关闭"></el-button>
            </div>
          </div>
          <div class="microModule-box-content">
            <component v-bind:is="item.mmd"></component>
          </div>
        </div>
      </div>
    
    </div>
    <!----拖拽布局end---->
  </div>
</template>

<script>
import dragReady from "./js_MicroModule"
import cygn from "./vmodules/cygn"
import dbsx from "./vmodules/dbsx"
import tzgg from "./vmodules/tzgg"

import xxsj from "./vmodules/xxsj"
import dyxx from "./vmodules/dyxx"
import rl from "./vmodules/rl"
import rcgl from "./vmodules/rcgl"
import tqyb from "./vmodules/tqyb"
import downLoad from "./vmodules/downLoad"

export default {
  components:{
    cygn,dbsx,tzgg,xxsj,dyxx,rl,rcgl,tqyb,downLoad
  },
  data() {
    return {
      drag_edit:false,
      show_grid:true,
      fixedHeight:false,//是否模块固定高度，高度固定后需要自己设定模块position里的高度属性
      MALactiveNames:["1","2"],
      selectColumnActive:3,
      selectColumn:[
        {id:1,value:[0]},
        {id:2,value:[0,6]},
        {id:3,value:[0,4,8]},
        {id:4,value:[0,3,6,9]},
        {id:6,value:[0,2,4,6,8,10]}
      ],
      moduleColumnWDTH:[4,4,4],//列宽相加不大于12
      moduleColumn:[0,4,8],//列坐标根据列宽形成
      cy_moduleColumnWDTH:[],
      cy_moduleColumn:[],
      Initial_modules_Data:[
        {title:"常用功能",show:true,id:"mm_0",mmd:"cygn",position:{x:0,y:1,w:4,h:3.5}},
        {title:"待办事项",show:true,id:"mm_1",mmd:"dbsx",position:{x:4,y:2,w:4,h:3.5}},
        {title:"通知公告",show:true,id:"mm_2",mmd:"tzgg",position:{x:8,y:3,w:4,h:3.5}},
        {title:"信息收集",show:true,id:"mm_3",mmd:"xxsj",position:{x:0,y:4,w:4,h:3.5}},
        {title:"订阅消息",show:true,id:"mm_5",mmd:"dyxx",position:{x:8,y:6,w:4,h:3.5}},
        {title:"日历",show:true,id:"mm_6",mmd:"rl",position:{x:0,y:7,w:4,h:3.5}},
        {title:"日程管理",show:true,id:"mm_4",mmd:"rcgl",position:{x:4,y:5,w:4,h:3.5}},
        {title:"天气预报",show:true,id:"mm_7",mmd:"tqyb",position:{x:4,y:8,w:4,h:3.5}},
        {title:"文件下载",show:true,id:"mm_8",mmd:"downLoad",position:{x:8,y:9,w:4,h:3.5}},
      ],
      drag_all_modules:[],
      setShow:false,
    }
  },
  methods: {
    //显示网格
    grid_show(el){
      this.show_grid = el;
    },

    //关闭一个模块
    close_module(name){
      this.drag_all_modules[name].show = false;
      setTimeout(()=>{
        dragReady.filtercopyDragElAll();
      })
    },

    //初始化
    initializationMMD(){
      this.$confirm('是否初始化内容，初始化后组件排列将恢复最初状态', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.drag_all_modules = JSON.parse(JSON.stringify(this.Initial_modules_Data));
        this.drag_all_modules.forEach(val=>{
          if(document.getElementById(val.id)){
            for(var po in val.position){
              document.getElementById(val.id).setAttribute("grid-"+po,val.position[po]);
            }
          }
        });
        this.setmoduleColumn();
        this.$message({
          type: 'success',
          message: '已成功初始化!'
        });
      }).catch((e) => {
        this.$message({
          type: 'info',
          message: '已取消'
        });          
      });
    },

    resetStart(){
      var nextRun=()=>{
        this.$confirm('重置后组件排列将恢复到上次保存的状态', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.ResetSort();
          this.$message({
            type: 'success',
            message: '已重置!'
          });
        }).catch((e) => {
          this.$message({
            type: 'info',
            message: '已取消'
          });          
        });
      };
      for(var i=0;i<this.drag_all_modules.length;i++){
        var val = this.drag_all_modules[i];
        var _that = document.getElementById(val.id);
        if(document.getElementById(val.id)){
            if(val.position.x*1 !==_that.getAttribute("grid-x")*1
            || val.position.y*1 !==_that.getAttribute("grid-y")*1
            || val.position.w*1 !==_that.getAttribute("grid-w")*1
            ){
            return nextRun()
          }
        }
      };
    },

    //内容重置
    ResetSort(){
      if(localStorage.getItem("drag_all_modules")){
        this.drag_all_modules = JSON.parse(localStorage.getItem("drag_all_modules"));
      };
      this.drag_all_modules.forEach(val=>{
        if(document.getElementById(val.id)){
          for(var po in val.position){
            document.getElementById(val.id).setAttribute("grid-"+po,val.position[po]);
          }
        }
      });
      this.cy_moduleColumn = JSON.parse(localStorage.getItem("cy_moduleColumn"));
      this.cy_moduleColumnWDTH = JSON.parse(localStorage.getItem("cy_moduleColumnWDTH"));
      this.setmoduleColumn()
    },

    //取消编辑
    stop_drag_edit(){
      var nextRun=()=>{
        this.$confirm('确认是否放弃本次编辑内容？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.drag_edit = false;
          this.ResetSort();
        }).catch((e) => {
          this.$message({
            type: 'info',
            message: '已取消'
          });          
        });
      };
      for(var i=0;i<this.drag_all_modules.length;i++){
        var val = this.drag_all_modules[i];
        var _that = document.getElementById(val.id);
        if(document.getElementById(val.id)){
            if(val.position.x*1 !==_that.getAttribute("grid-x")*1
            || val.position.y*1 !==_that.getAttribute("grid-y")*1
            || val.position.w*1 !==_that.getAttribute("grid-w")*1
            ){
            return nextRun()
          }
        }
      };
      this.drag_edit = false;
      this.ResetSort()
    },

    //启动编辑
    start_drag_edit(){
      this.drag_edit = true;
      setTimeout(()=>{
        dragReady.initialization_drag()
      })
    },

    //保存编辑
    save_drag_edit(){
      this.$confirm('是否保存当前编辑的内容?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.drag_all_modules.forEach(val=>{
          if(document.getElementById(val.id)){
            val.position = {
              x:document.getElementById(val.id).getAttribute("grid-x")*1,
              y:document.getElementById(val.id).getAttribute("grid-y")*1,
              w:document.getElementById(val.id).getAttribute("grid-w")*1,
              h:document.getElementById(val.id).getAttribute("grid-h")*1,
            }
          }
        });
        localStorage.setItem("drag_all_modules",JSON.stringify(this.drag_all_modules));
        localStorage.setItem("cy_moduleColumn",JSON.stringify(this.cy_moduleColumn));
        localStorage.setItem("cy_moduleColumnWDTH",JSON.stringify(this.cy_moduleColumnWDTH));
        this.drag_edit = false;
        this.$message({
          type: 'success',
          message: '保存成功!'
        });
      }).catch((e) => {
        console.log(e)
        this.$message({
          type: 'info',
          message: '已取消'
        });          
      });
    },

    //切换显示模块
    changeMDshow(){
      setTimeout(()=>{
        dragReady.initialization_drag();
        dragReady.filtercopyDragElAll()
      })
    },
    

    //切换行列数
    changeModuleColumn(val){
      var moduleColumnWDTH = [];
      var alllCOUM = [];
      var EndalllCOUM=[];
      for(var i=0;i<this.Initial_modules_Data.length;i+=val.length){
        alllCOUM.push(this.Initial_modules_Data.slice(i,i+val.length))
      };
      // var Math.ceil()
      val.forEach((vl,index)=>{
        if(index>0){
          moduleColumnWDTH.push(vl-val[index-1])
        };
        if(index===val.length-1){
          moduleColumnWDTH.push(12-vl)
        }
      });
      alllCOUM.forEach((vvl,inn)=>{
        vvl.forEach((vs,index)=>{
          EndalllCOUM.push(vs)
          if(document.getElementById(vs.id)){
            document.getElementById(vs.id).setAttribute("grid-x",val[index]),
            document.getElementById(vs.id).setAttribute("grid-y",inn),
            document.getElementById(vs.id).setAttribute("grid-w",moduleColumnWDTH[index]),
            document.getElementById(vs.id).setAttribute("grid-h",vs.position.h);
          }
        })
      });
      this.setmoduleColumn();
      console.log(val,moduleColumnWDTH,alllCOUM);
    },

    //设置列宽以及列数
    setmoduleColumn(h,x,w){
      if(h&&x&&w){
        dragReady.initialization_drag(h,x,w);
      }else{
        dragReady.initialization_drag(this.fixedHeight,this.cy_moduleColumnWDTH,this.cy_moduleColumn);
      };
      setTimeout(()=>{
        dragReady.initialization_drag()
      });
    }
  },
  computed: {
  },
  watch: {
    drag_edit(val){
      if(val){
        this.start_drag_edit()
      }else{
      }
    }
  },
  created() {
    if(localStorage.getItem("drag_all_modules") && localStorage.getItem("drag_all_modules")!==""){
      this.drag_all_modules = JSON.parse(localStorage.getItem("drag_all_modules"));
    }else{
      this.drag_all_modules = JSON.parse(JSON.stringify(this.Initial_modules_Data));
      localStorage.setItem("drag_all_modules",JSON.stringify(this.drag_all_modules))
    };
    if(localStorage.getItem("cy_moduleColumnWDTH")){
      this.cy_moduleColumnWDTH=JSON.parse(localStorage.getItem("cy_moduleColumnWDTH"));
    }else{
      this.cy_moduleColumnWDTH=JSON.parse(JSON.stringify(this.moduleColumnWDTH));
      localStorage.setItem("cy_moduleColumnWDTH",JSON.stringify(this.cy_moduleColumnWDTH));
    };
    if(localStorage.getItem("cy_moduleColumn")){
      this.cy_moduleColumn=JSON.parse(localStorage.getItem("cy_moduleColumn"));
    }else{
      this.cy_moduleColumn=JSON.parse(JSON.stringify(this.moduleColumn));
      localStorage.setItem("cy_moduleColumn",JSON.stringify(this.cy_moduleColumn))
    };
  },
  mounted (){
    // dragReady.initialization_drag(this.fixedHeight)
    this.setmoduleColumn();
  }
}
</script>
<style lang="scss" scoped>
#microModule{
  background-color:#f5f5f5;
  max-width: 1400px;
  padding:0px 20px 20px 20px;
  position: relative;
  width: 100%;
  min-height: 100%;
  -webkit-box-sizing: border-box;
  box-sizing: border-box;
  display: block;
  margin:0 auto;
  // flex: 1;

  .microModule-box{
    margin:10px 12px;
    display: flex;
    flex: 1;
    background-color:#ffffff;
    height: calc(100% - 20px);
    box-shadow: 0px 4px 12px rgba(0,0,0,0.1);
    flex-direction: column;
    .microModule-box-tile{
      display: flex;
      flex-direction: row;
      padding: 0 20px;
      height: 50px;
      width: 100%;
      box-sizing: border-box;
      border-top:2px #2d83ea solid;
      border-bottom:1px #eeeeee solid;
      justify-content: center;
      span{
        color: #333333;
        font-size: 18px;
        margin: auto 0;
      }
      button{
        font-size: 24px;
        color:#999999;
      }
      button:hover{color:#2d83ea;}
  
    }

    .microModule-box-content{
      display: flex;
      flex: 1;
      overflow: hidden;
      flex-direction: column;
    }
  }
}


.MicroAssemblyCenter{
  position: absolute;
  top: 50px;
  z-index: 9999999;
  background-color: #ffffff;
  width: 350px;
  box-shadow:0 4px 10px rgba(0,0,0,0.1);
  // overflow: auto;
  padding: 0 0px 20px 0px;
  .MicroAssemblyCenter-title{
    display: flex;
    height: 50px;
    align-items: center;
    // justify-content: center;
    // border-bottom:1px #dddddd solid;
    font-size: 18px;
    color:#2d83ea;
    padding: 0 10px;
    background: #fafafa;
  }
  .el-collapse-item__header{
    color: #333333;
    .header-icon{
      color:#2d83ea;
      font-size: 18px;
    }
  }
  .el-collapse{
    padding: 0 10px;
    max-height: calc(100vh - 200px);
    height: auto;
    overflow: auto;
    position: relative;
  }
  .MALactiveItem{
    padding: 4px 10px;
    display: flex;
    align-items: center;
    height: 36px;
    & > span{
      margin-left: 20px;
      color:#666666;
    }
  }
}
</style>
<style lang="scss">
.MicroAssemblyCenter{
  .el-collapse-item__header.is-active{
    border-bottom:1px #EBEEF5 solid;
  }
  .el-collapse-item__content{
    padding-bottom: 15px;
  }
}
</style>